<template>
  <div>
    <!-- :EndColumnsData="EndColumnsData"  :cellStyle="cellStyle"-->
    <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
      :isFixedColumn="true" :columnWidth="200" :isMore="false" :isEndColumns="false" :footerBtnList="footerBtnList"
      :tableLoading="loading" :total="total" 
      @pageSize="handlePageSize" @currentPage="handleCurrentPage">
      <!-- 条件组,插槽 -->
      <template #default>
        <el-form :inline="true" :model="formBtnList" class="demo-form-inline" @submit.native.prevent>
          <el-form-item label="举报类型">
            <el-select v-model="formBtnList.reported_type" placeholder="全部" style="width: 90px" @change="handleOnSelect">
              <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formBtnList.status" placeholder="状态" @change="handleOnSelect" style="width: 100px">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="举报ID">
            <el-input v-model="formBtnList.report_id" :prefix-icon="Search" placeholder="举报ID" style="width: 120px" />
          </el-form-item>
          <el-form-item label="举报人ID">
            <el-input v-model="formBtnList.user_id" :prefix-icon="Search" placeholder="举报人ID" style="width: 130px"/>
          </el-form-item>
          <el-form-item label="被举报人ID">
            <el-input v-model="formBtnList.reported_user_id" :prefix-icon="Search" placeholder="被举报人ID" style="width: 130px"/>
          </el-form-item>
          <el-form-item label="举报时间">
            <el-date-picker v-model="dateList" style="width: 220px" type="daterange" unlink-panels range-separator="-"
              start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" value-format="YYYY-MM-DD"
              format="YYYY-MM-DD" @change="handleDateChange" />
            </el-form-item>
        </el-form>
      </template>
    </Table>
    <reportManagementDialog ref="dialogCom" :dialogVisible="dialogVisible2" :btnLoading="btnLoading2"
      :ruleForm="ruleForm" :tableTitle="tableTitle2" :isStatus="isStatus"
      @beforeClose="beforeClose" @submitForm="submitForm">
    </reportManagementDialog>
  </div>
</template>

<script setup lang='ts' name="report">
import { ref, reactive, onMounted} from 'vue'
import { formatter, type FormRules, type TableColumnCtx } from 'element-plus'
import Table from '@/components/Table.vue';
import reportManagementDialog from './reportManagementDialog.vue';
import DialogCom from '@/components/DialogCom.vue';
import { Search } from '@element-plus/icons-vue'
import { getReportList, getReportDetail,handleReport } from '@/api/report/report'
import { useRouteStore } from '@/stores/modules/counter.ts'
const routeStore = useRouteStore();
// 表格相关 开始
const loading = ref(false)
const btnLoading2 = ref(false)
const tableTitle2 = ref('');
const isStatus = ref(-1) //传给子组件 状态是否是已处理
// 定义分类映射类型
type ReportCateMap = {
  '1': string;
  '2': string;
  '3': string;
  '4': string;
  '5': string;
  '6': string;
  '7': string;
  '8': string;
  '9': string;
  '10': string;
};
// 定义违规分类映射关系
const reportCateMap = ref<ReportCateMap>({
  '1': '血腥暴力',
  '2': '色情低俗',
  '3': '侵犯权益',
  '4': '造谣抹黑',
  '5': '人身攻击',
  '6': '引战骚扰',
  '7': '广告营销',
  '8': '侮辱英烈',
  '9': '违法违规',
  '10': '其他'
});
// 格式化举报分类字段（report_reason_type）
const formatReportCate = (row: any) => {
  const typeValue = row.report_reason_type as string
  return reportCateMap.value[typeValue as keyof ReportCateMap] || '';
};
// 格式化类型字段（reported_type）
const formatReportType = (row: any) => {
  if (row.reported_type === '1') {
    return '内容';
  }else if (row.reported_type === '2') {
    return '评论';
  }
  return '全部';
};
// 格式化状态字段（status）
const formatStatus = (row: any) => {
  if (row.status === '1') {
    return '已处理';
  } else if (row.status === '0') {
    return '待处理';
  }
  return '全部';
};
  // 表头基础列配置
  const columns = [
    { prop: 'report_id', label: '举报ID', width: 100 },
    { prop: 'reported_type', label: '举报类型', width: 110 , formatter:formatReportType},
    { prop: 'user_id', label: '举报人用户ID', width: 140 },
    { prop: 'report_reason_type', label: '举报分类', width: "",formatter:formatReportCate},
    { prop: 'add_time', label: '举报时间', width: 180 },
    { prop: 'reported_user_id', label: '被举报人ID', width: 140 },
    { prop: 'reported_id', label: '内容ID/评论ID', width: 160 },
    { prop: 'status', label: '状态', width: 100, formatter: formatStatus },
    { prop: 'handle_time', label: '处理时间', width: 180}
  ];

// 固定最右侧列
// const EndColumnsData = ref({ prop: 'status', label: '状态', width: 130, formatter: (row: any) => row.status == '1' ? '已上架' : '已下架' })

// 表格数据
// 判断依据: judData
interface ReportListType {
  report_id: number,          //举报id
  reported_id: number,        //被举报的帖子id或者评论id
  user_id: number,            //举报人id
  reported_type: string,      //举报类型（1.帖子，2评论）
  reported_user_id: number,   //被举报人id
  reason: string,             //举报原因说明
  status: string,             //是否处理 0 1
  handler_account: string,    //处理人账户（管理员）
  report_reason_type: string, //举报分类（0-9）
  handle_time: string,        //处理时间
  add_time: string,           //举报时间
  judData?:string             //显示按钮  自加
}
// 详情页数据
interface RuleFormItem {
  reported_user_id?: number;  //被举报人id
  user_name?: string;         //用户名  x
  report_reason_type?: string, //举报分类（0-9）
  reason?: string;            //举报原因
  handle_type?:string;        // 处理方式（0:不违规，1：违规并有封禁时间，2封号） √
  limit_time?:number;         //限制时长（单位：天，uint32） handle_type为1的时候才会有时间
  handle_remark?:string;      //操作理由 √

  report_handle_id?:number;   //处理id？
  report_id?:number;          //举报id
  handler_account?:string;     //处理人账户（管理员）
  handle_time?:string         //处理时间
  status?:string              //是否处理
  action?:string              // ?
  unsealing_time?:string
}
const paginatedData = ref<ReportListType[]>([])
// 处理和详情 表格数据
const ruleForm = ref<RuleFormItem[]>([]);
// 详情接口获取的数据
const detail = ref<RuleFormItem>({})
// 查询条件
const formBtnList = reactive({
  reported_type: '',
  status: '',
  report_id: '',
  user_id: '',
  reported_user_id: '',
  time_start: '',
  time_end: '',
  pageSize: 10,
  page: 1,
})
const dateList = ref([])
// 日期快速选择
const shortcuts = [
  {
    text: '近1周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近90天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]
// 日期选择
const handleDateChange = () => {
  formBtnList.time_start = dateList.value[0]
  formBtnList.time_end = dateList.value[1]
}
const handleOnSelect = () => {
  handInquire()
}
let typeOptions = ref([
  {
    value: '',
    label: '全部',
  },
  {
    value: '1',
    label: '内容',
  },
  {
    value: '2',
    label: '评论',
  },
])
let statusOptions = ref([
  {
    value: '',
    label: '全部',
  },
  {
    value: '0',
    label: '待处理',
  },
  {
    value: '1',
    label: '已处理',
  },
])
const total = ref(0)
// 获取举报列表数据 参数 formBtnList
const handInquire = () => {
  loading.value = true
  // formBtnList
  getReportList(formBtnList).then((res: any) => {
    if (res.code === 200) {
      total.value = res.data.total
      if (res.data.total === 0) {
        paginatedData.value = []
        ElMessage.error(`没有举报数据`)
        return
      }
      const processedData = res.data.reports.map((item: ReportListType) => {
        return {
          ...item,
          judData: item.status  //添加  judData  属性，并赋值为 status
        };
      });
      paginatedData.value = processedData
    } else {
      paginatedData.value = []
      ElMessage.error(`获取举报数据失败: ${res.msg}`)
    }
  }).catch((error: any) => {
    paginatedData.value = []
    ElMessage.error(`请求错误: ${error}`)
  }).finally(() => {
    loading.value = false
  })
}

// 获取举报详情 参数 
const getDetail = (id:string) =>{
  detail.value= {}
  loading.value = true
  getReportDetail(id).then((res: any) => {
    if (res.code === 200) {
      console.log('举报详情',res.data)
      // ruleForm.value[0] = res.data
      detail.value = res.data
      getRuleForm(Number(id))
      ruleForm.value[0].handle_type=detail.value?.handle_type
      ruleForm.value[0].unsealing_time=detail.value?.unsealing_time
      ruleForm.value[0].handle_remark=detail.value?.handle_remark
      ruleForm.value[0].handler_account=detail.value?.handler_account
      console.log("ruleForm.value",ruleForm.value);
    } else{
      // ruleForm.value= []
      ElMessage.error(`详情获取失败:${res.msg}`)
    }
  }).catch((error: any) => {
    // ruleForm.value = []
    ElMessage.error(`请求错误: ${error}`)
  }).finally(() => {
    loading.value = false
  })
}

// interface RuleForm {
//   handle_type: string,  // 1 内容评论封禁 2 账号封禁  0不做处理
//   handle_remark:string
// }

// 从表中筛选ruleForm的只读内容
function getRuleForm(id:number){
  ruleForm.value =[]
  const targetItem = paginatedData.value.find(item => item.report_id === id);
  // 2. 提取其他字段（排除 id）
  if (targetItem) {
    // 创建符合格式的新对象，从 targetItem 中取需要的字段，其他字段按需求补充
    const newItem = {
      reported_user_id: targetItem.reported_user_id, // 从目标项获取
      // user_name:targetItem.user_name,
      report_reason_type: targetItem.report_reason_type, // 从目标项获取
      reason: targetItem.reason, // 从目标项获取
      handler_account:localStorage.getItem('userName') || '',
      handle_type: "", // 固定空值或其他默认值
      handle_remark: "", // 固定值或根据需求动态设置
      limit_time: 3, // 固定值或根据需求动态设置
      report_id:id,          //举报id
      unsealing_time:''
    };
    // 向空数组中添加新对象
    ruleForm.value.push(newItem);
  } else {
    console.log("未找到项");
  }
} 

// 处理弹窗 handle
const handle = (row: any, index: number) => {
  console.log(index);
  // todo 获取详情？// getDetail(String(row.report_id))
  getRuleForm(row.report_id)
  tableTitle2.value = '举报处理'
  isStatus.value = 0
  dialogVisible2.value = true
}
// 详情弹窗
const details = (row: any, index: number) => {
  console.log(index);
  // todo 获取详情 
  getDetail(row.report_id)
  tableTitle2.value = '举报详情'
  isStatus.value =1
  dialogVisible2.value = true
}

// 弹窗 确认按钮 (ruleFormData: any)
const submitForm = (ruleFormData:any) => {
  // 1. 从 ruleFormData 中提取已知字段
  const baseParam = {
    reported_user_id: ruleFormData.reported_user_id, // 被举报人id（来自 ruleFormData）
    report_id: ruleFormData.report_id,               // 举报id（来自 ruleFormData）
    handle_type: ruleFormData.handle_type,           // 处理方式（来自 ruleFormData）
    handle_remark: ruleFormData.handle_remark,       // 操作理由（来自 ruleFormData）
    limit_time: ruleFormData.limit_time              // 限制时长（来自 ruleFormData，handle_type=1 时有效）
  };
  // 2. 根据 report_id 在 paginatedData 中匹配对应项
  const matchedItem = paginatedData.value.find(
    (item) => item.report_id === ruleFormData.report_id
  );

  if (!matchedItem) {
    console.error("未找到匹配的举报数据，请检查 report_id");
    return; // 未匹配到数据时终止执行
  }
  // 3. 从匹配项中提取剩余所需字段，合并生成 handleParam
  const handleParam = {
    ...baseParam,
    reported_type: matchedItem.reported_type,    // 举报类型（帖子/评论，来自 paginatedData）
    user_id: matchedItem.user_id,                // 举报人id（来自 paginatedData）
    reported_id: matchedItem.reported_id,        // 被举报的帖子/评论id（来自 paginatedData）
    handler_account: localStorage.getItem('userName') // 处理人账户（来自 paginatedData，可能需要管理员信息）
  };
  console.log("处理参数",handleParam)
    // 处理举报
    handleReport(handleParam).then((res)=>{
      if(res.code == 200){
        console.log('处理成功',res)
        handInquire()
      }else{
        ElMessage.error(`${res.msg}`)
        console.error("处理失败", res.msg);
      }
    }).catch((err) => {
      ElMessage.error(`${err.msg}`)
  }).finally(()=>{
      dialogVisible2.value = false
  });
}

// 重置
const handDerived = () => {
  // console.log('重置')
  formBtnList.reported_type='',
  formBtnList.status='',
  formBtnList.report_id='',
  formBtnList.user_id='',
  formBtnList.time_start= '',
  formBtnList.time_end = '',
  formBtnList.reported_user_id='',
  // formBtnList.pageSize= 10,
  // formBtnList.page= 1,
  dateList.value = []
  handInquire()
}
// 按钮组
const btnList = [
  { name: '查询', type: 'primary', click: handInquire, icon: '' },
  { name: '重置', type: 'success', click: handDerived, icon: '' },
]
const footerBtnList: any[] = [
  // { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
]
// 删除
// const reject = (row: any, index: number) => {
//   console.log(index)
//   ElMessageBox.confirm(
//     '确定删除此项吗？',
//     '删除',
//     {
//       confirmButtonText: '是',
//       cancelButtonText: '否',
//       type: 'warning',
//     }
//   ).then(() => {
//     reportDel(row.report_id).then((res: any) => {
//       if (res.code === 200) {
//         ElMessage({
//           message: '成功',
//           type: 'success',
//         })
//       } else {
//         ElMessage.error(`请求错误: ${res.msg}`)
//       }
//     }).catch(() => {
//     }).finally(() => {
//       handInquire()
//     })
//   }).catch(() => {
//   })
// }

// 操作列按钮组
const btnListTable = ref([
  { name: '处理', type: 'success', click: handle, judgment: true, isShow: ['0'],color:'#F77381'},
  { name: '处理详情', type: 'primary', click: details, judgment: true, isShow: ['1'],color:'#81B337'},
  // { name: '删除', type: 'danger', click: reject },
])
// 分页事件触发
const handlePageSize = (pageSize: number) => {// 每页大小
  console.log('handlePageSize', pageSize);
  formBtnList.pageSize = pageSize
  handInquire()
};
const handleCurrentPage = (currentPage: number) => {// 页码
  // console.log('handleCurrentPage', currentPage);
  formBtnList.page = currentPage
  handInquire()
};
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();

const dialogVisible2 = ref(false);
const beforeClose = () => {
  dialogVisible2.value = false;
}
onMounted(() => {
  handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
  .el-input {
    width: 160px;
  }

  :deep(.el-date-editor) {
    width: 240px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 20px;
  }
}
</style>